package com.gpstracker.services;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.gpstracker.db.MyDatabase;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.ProgressBar;

public class UploadDataService extends Service{

	public static final String CUSTOM_INTENT_START = "action.Progress_start";
	public static final String CUSTOM_INTENT_COMPLETE = "action.Progress_stop";
	public static final String CUSTOM_INTENT_ERROR = "action.ERROR";

	private static final String tag = "UPLOAD_DATA_SERVICE";

	ArrayList<NameValuePair> nameValuePairs;
	TelephonyManager telephonyManager;
	String dbServer;

	ProgressBar progressBar;
	int myProgress;
	private Context ctx;
	private String imei;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		ctx = getApplicationContext();
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

		telephonyManager = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
		nameValuePairs = new ArrayList<NameValuePair>();

		imei = prefs.getString("imei", "");
		if(imei.equals(""))
			imei = telephonyManager.getDeviceId();


		nameValuePairs.add(new BasicNameValuePair("imei", imei));


		dbServer = prefs.getString("dbServer", "192.168.0.101");
		if(dbServer.equals(""))
			dbServer="192.168.0.101";
		Log.d("DB_SERVER", dbServer);

		new Uploader().execute();
		this.stopSelf();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	private class Uploader extends AsyncTask<Void, Integer, Void>{

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			InputStream is = null;
			String result=null;

			publishProgress(0);


			try{
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost("http://"+dbServer+"/checkUser.php");

				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();

			}catch(Exception e){
				Log.e("log_tag", "Error in http connection "+e.toString());
			}

			//convert response to string
			try{

				BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();

				result=sb.toString();
				Log.i(tag, "1-result: "+result);
				if(result.length()<=2)
					result=result.substring(0, 1);
				if(result.equals("0")){
					publishProgress(-1);
					return null;
				}

			}catch(Exception e){
				Log.e("log_tag", "Error converting result "+e.toString());
			}



			MyDatabase myDatabase = new MyDatabase(ctx);
			myDatabase.open();
			Cursor cursor = myDatabase.getLocationsToUpload(result);

			cursor.moveToFirst();
			while (cursor.isAfterLast() == false) 
			{
				Log.i(tag, "record!!!!");
				float lon = cursor.getFloat(1);
				float lat = cursor.getFloat(2);
				String provider = cursor.getString(3).substring(0, 1);
				Integer fulltime = cursor.getInt(4);
				int offset = cursor.getInt(5)/3600000;
				float accuracy = cursor.getFloat(6);
				String string_time = cursor.getString(7);
				float speed = cursor.getFloat(8);
				String mode = cursor.getString(9);

				nameValuePairs.clear();
				nameValuePairs.add(new BasicNameValuePair("imei", imei));
				nameValuePairs.add(new BasicNameValuePair("lat", String.valueOf(lat)));
				nameValuePairs.add(new BasicNameValuePair("lon", String.valueOf(lon)));
				nameValuePairs.add(new BasicNameValuePair("provider", provider));
				nameValuePairs.add(new BasicNameValuePair("fulltime", String.valueOf(fulltime)));
				nameValuePairs.add(new BasicNameValuePair("offset", String.valueOf(offset)));
				nameValuePairs.add(new BasicNameValuePair("accuracy", String.valueOf(accuracy)));
				nameValuePairs.add(new BasicNameValuePair("string_time", string_time));				
				nameValuePairs.add(new BasicNameValuePair("speed", String.valueOf(speed)));
				nameValuePairs.add(new BasicNameValuePair("mode", mode));
				try{
					HttpClient httpclient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost("http://"+dbServer+"/insertLocation.php");

					Log.i("namevaluepairs",nameValuePairs.toString());

					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

					HttpResponse response = httpclient.execute(httppost);
					HttpEntity entity = response.getEntity();
					is = entity.getContent();

				}catch(Exception e){
					Log.e("log_tag", "Error in http connection "+e.toString());
				}

				/****************************************************************************************/
				//cancella da qua a 
				
//				if(mode.equals("subway")){
//
//					Log.i(tag, "record!!!!");
//					
//					fulltime++;
//					nameValuePairs.clear();
//					nameValuePairs.add(new BasicNameValuePair("imei", imei));
//					nameValuePairs.add(new BasicNameValuePair("lat", String.valueOf(lat)));
//					nameValuePairs.add(new BasicNameValuePair("lon", String.valueOf(lon)));
//					nameValuePairs.add(new BasicNameValuePair("provider", provider));
//					nameValuePairs.add(new BasicNameValuePair("fulltime", String.valueOf(fulltime)));
//					nameValuePairs.add(new BasicNameValuePair("offset", String.valueOf(offset)));
//					nameValuePairs.add(new BasicNameValuePair("accuracy", String.valueOf(accuracy)));
//					nameValuePairs.add(new BasicNameValuePair("string_time", string_time));				
//					nameValuePairs.add(new BasicNameValuePair("speed", String.valueOf(speed)));
//					nameValuePairs.add(new BasicNameValuePair("mode", mode));
//					try{
//						HttpClient httpclient = new DefaultHttpClient();
//						HttpPost httppost = new HttpPost("http://"+dbServer+"/insertLocation.php");
//
//						Log.i("namevaluepairs",nameValuePairs.toString());
//
//						httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//
//						HttpResponse response = httpclient.execute(httppost);
//						HttpEntity entity = response.getEntity();
//						is = entity.getContent();
//
//					}catch(Exception e){
//						Log.e("log_tag", "Error in http connection "+e.toString());
//					}
//
//				}

				//qua
				/*****************************************************************************************************/
				
				cursor.moveToNext();
			}


			publishProgress(1);
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			Intent i = new Intent();
			Log.i("onprogressupdate", String.valueOf(progress[0]));
			if (progress[0] == 0){
				i.setAction(CUSTOM_INTENT_START);
				Log.i("onprogressupdate", CUSTOM_INTENT_START);
			}
			if (progress[0] == 1){
				i.setAction(CUSTOM_INTENT_COMPLETE);
				Log.i("onprogressupdate", CUSTOM_INTENT_COMPLETE);
			}
			if (progress[0] == -1){
				i.setAction(CUSTOM_INTENT_ERROR);
				Log.i("onprogressupdate", CUSTOM_INTENT_ERROR);		
			}

			ctx.sendBroadcast(i);
		}
	}
}
